package com.liuyi.netty.im.test.modular.websocket;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

/**
 * @author Mr.Fmy
 * @since 2022/1/21
 */
@Component
@ServerEndpoint("/pressureTest")
@Slf4j
public class WsServerEndpoint {

    private static Session session;

    /**
     * 连接成功
     */
    @OnOpen
    public void onOpen(Session session) {
        WsServerEndpoint.session = session;
    }

    /**
     * 连接关闭
     */
    @OnClose
    public void onClose(Session session) {
        // 判断当前连接是否还在线
        if (session.isOpen()) {
            try {
                // 关闭连接
                CloseReason closeReason = new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE, "鉴权失败！");
                session.close(closeReason);
                WsServerEndpoint.session = null;
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error(error.getMessage(), error);
    }

    public static void sendMsg(WsMsg msg) {
        try {
            if (WsServerEndpoint.session != null) {
                WsServerEndpoint.session.getBasicRemote().sendText(JSONObject.toJSONString(msg));
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}
